package com.ftp.web.spider.service.mediaservice;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.helper.HttpConnection;
import org.springframework.stereotype.Component;

/**
 *
 * @author FbiWaring
 *
 */
@Component
public class DownloadService {
	
	
	public void downloadHttpLink(String savePath,String link) {
		if (link.isBlank()) {
			return;
		}
		try {
			URL url = new URL(link);
	        HttpURLConnection conn;
			conn = (HttpURLConnection)url.openConnection();
	        //设置超时时间
	        conn.setConnectTimeout(3*1000);
	        //设置请求头
	        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.50");
	        //conn.setRequestProperty("lfwywxqyh_token",toekn);
	
	        //打开输入流
	        InputStream inputStream = conn.getInputStream();
	        //设置读取字节码长度
	        byte[] getData = readInputStream(inputStream);
	
	        //设置文件存储路径
	        File saveDir = new File(savePath);
	        if(!saveDir.exists()){
	            saveDir.mkdir();
	        }
	        File file = new File(saveDir+File.separator+link.substring(link.lastIndexOf("/")+1));
	        FileOutputStream fos = new FileOutputStream(file);
	        fos.write(getData);
	        if(fos!=null){
	            fos.close();
	        }
	        if(inputStream!=null){
	            inputStream.close();
	        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


        System.out.println("info:"+link+" download success");
	}

	 public  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
	 
	 /*public static void main(String[] args) {
		String aString="[����] СҰ����w-��װJK [24P] - �r�����҂� | ������^ - t66y.com";
		//System.out.println(aString.lastIndexOf(".")+"-----"+aString.lastIndexOf("/"));
		String titleString=aString.substring(aString.indexOf("["), aString.lastIndexOf("]")+1).intern();
		System.out.println(titleString.substring(titleString.indexOf("]")+1,titleString.lastIndexOf("[")).trim());
	}*/
}
